<template>
    <div class="add-cargo-owner-page">
        <div class="page-title">修改货主</div>

        <div class="form card">
            <div class="form-item required">
                <label class="label">货主姓名：</label>
                <input class="input" v-model.trim="form.name" placeholder="请输入货主姓名" />
            </div>

            <div class="form-item required">
                <label class="label">手机号：</label>
                <input class="input" v-model.trim="form.phone" placeholder="请输入手机号" />
            </div>

            <div class="form-item required">
                <label class="label">单位名称：</label>
                <select class="input" v-model="form.company" @change="onCompanyChange">
                    <option value="" disabled>请选择单位名称</option>
                    <option v-for="u in externalUnitOptions" :key="u.id" :value="u.unitName">{{ u.unitName }}</option>
                </select>
            </div>

            <div class="form-item required">
                <label class="label">联系地址：</label>
                <select class="input" v-model="form.address">
                    <option value="" disabled>请选择联系地址</option>
                    <option v-for="a in addressOptions" :key="a" :value="a">{{ a }}</option>
                </select>
            </div>

            <div class="form-item required">
                <label class="label">驾驶证有效日期：</label>
                <input class="input" type="date" v-model="form.licenseExpireDate" placeholder="请选择驾驶证有效日期" />
            </div>

            <div class="form-item">
                <label class="label">备 注：</label>
                <textarea class="textarea" v-model.trim="form.remark" placeholder="请输入备注信息"></textarea>
            </div>

            <div class="form-item">
                <label class="label">驾驶证照片：</label>
                <div class="upload-box" @click="triggerSelect">
                    <input ref="fileInput" class="file-input" type="file" accept="image/*" @change="onFileChange" />
                    <div v-if="!previewUrl" class="uploader">
                        <div class="plus">+</div>
                        <div class="text">上传图片</div>
                    </div>
                    <img v-else :src="previewUrl" class="preview" alt="preview" />
                </div>
            </div>

            <div class="form-actions">
                <button class="btn primary" :disabled="submitting" @click="handleSubmit">保存</button>
                <button class="btn" @click="handleCancel">取消</button>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { read, write } from '@/assets/Axios/axiosHttple'

interface UpdateCargoOwnerDto {
    id?: number
    name: string
    phone: string
    company: string
    address: string
    licenseExpireDate: string
    remark: string
    licenseImageFile?: File | null
    licenseImageUrl?: string
}

const form = reactive<UpdateCargoOwnerDto>({
    id: undefined,
    name: '',
    phone: '',
    company: '',
    address: '',
    licenseExpireDate: '',
    remark: '',
    licenseImageFile: null,
    licenseImageUrl: ''
})

const submitting = ref(false)
const fileInput = ref<HTMLInputElement | null>(null)
const previewUrl = ref<string>('')
const route = useRoute()

// 外协单位下拉数据
type ExternalUnit = { id: number; unitName: string; address: string }
const externalUnitOptions = ref<ExternalUnit[]>([])
const addressOptions = ref<string[]>([])

async function loadExternalUnits() {
    try {
        const res = await read.get('baseinforead/api/External/GetExternalList', { params: { PageIndex: 1, PageSize: 2000 } })
        let json: any = res?.data ?? { data: [] }
        const list = Array.isArray(json?.data?.data) ? json.data.data : (Array.isArray(json?.data) ? json.data : [])
        externalUnitOptions.value = (list || []).map((x: any) => ({
            id: x.id,
            unitName: x.unitName ?? '',
            address: x.address ?? x.contactAddress ?? ''
        }))
    } catch (e) {
        console.error('加载外协单位失败', e)
        externalUnitOptions.value = []
    }
}

function onCompanyChange() {
    const match = externalUnitOptions.value.find(u => u.unitName === form.company)
    addressOptions.value = []
    if (match && match.address) {
        addressOptions.value = [match.address]
        form.address = match.address
    } else {
        form.address = ''
    }
}

// 当详情或下拉数据就绪时，同步一次地址选项并保留原值
function syncAddressOptionsFromCompany() {
    const match = externalUnitOptions.value.find(u => u.unitName === form.company)
    addressOptions.value = []
    if (match && match.address) addressOptions.value = [match.address]
    // 如果详情里的地址与下拉地址不同，也加入选项，确保能显示
    if (form.address && !addressOptions.value.includes(form.address)) {
        addressOptions.value.unshift(form.address)
    }
}

function validate(): string | null {
    if (!form.name) return '请输入货主姓名'
    if (!form.phone) return '请输入手机号'
    if (!/^\d{6,20}$/.test(form.phone)) return '手机号格式不正确'
    if (!form.company) return '请输入单位名称'
    if (!form.address) return '请输入联系地址'
    if (!form.licenseExpireDate) return '请选择驾驶证有效日期'
    return null
}

function triggerSelect() { fileInput.value?.click() }

function onFileChange(e: Event) {
    const files = (e.target as HTMLInputElement).files
    if (!files || !files[0]) return
    const file = files[0]
    form.licenseImageFile = file
    const reader = new FileReader()
    reader.onload = () => { previewUrl.value = String(reader.result || '') }
    reader.readAsDataURL(file)
}

async function loadDetail(id: number) {
    // 尝试 1：GET ?id= 的查询参数方式
    const tryGetWithQuery = async () => {
        try {
            const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerById', { params: { id } })
            let json: any = res?.data ?? { code: res?.status, data: null }
            return json?.data || null
        } catch { return null }
    }

    // 尝试 2：GET 路径参数方式 /{id}
    const tryGetWithPath = async () => {
        try {
            const res = await read.get(`baseinforead/api/CargoOwner/GetCargoOwnerById/${encodeURIComponent(String(id))}`)
            let json: any = res?.data ?? { code: res?.status, data: null }
            return json?.data || null
        } catch { return null }
    }

    // 尝试 3：列表接口本地匹配兜底
    const tryFindFromList = async () => {
        try {
            const res = await read.get('baseinforead/api/CargoOwner/GetCargoOwnerList', { params: { PageIndex: 1, PageSize: 2000 } })
            let j: any = res?.data ?? { data: [] }
            const arr = Array.isArray(j?.data?.data) ? j.data.data : (Array.isArray(j?.data) ? j.data : [])
            return (arr || []).find((x: any) => Number(x?.id) === id) || null
        } catch { return null }
    }

    const data = await tryGetWithQuery() || await tryGetWithPath() || await tryFindFromList()
    if (!data) return

    form.name = data.ownerName ?? data.name ?? ''
    form.phone = data.phoneNumber ?? data.phone ?? ''
    form.company = data.unitName ?? data.company ?? ''
    form.address = data.contactAddress ?? data.address ?? ''
    form.licenseExpireDate = (data.licenseValidDate || '').slice(0, 10)
    form.remark = data.remarks ?? data.remark ?? ''
    form.licenseImageUrl = data.licensePhoto ?? ''
    previewUrl.value = form.licenseImageUrl || ''

    // 同步下拉选项，确保显示与可选
    syncAddressOptionsFromCompany()
}

async function handleSubmit() {
    const msg = validate()
    if (msg) return
    submitting.value = true
    try {
        const payload = {
            id: form.id ?? 0,
            ownerName: form.name,
            phoneNumber: form.phone,
            unitName: form.company,
            contactAddress: form.address,
            licenseValidDate: form.licenseExpireDate ? new Date(form.licenseExpireDate).toISOString() : '',
            remarks: form.remark,
            licensePhoto: previewUrl.value || form.licenseImageUrl || '',
            lastModifiedBy: localStorage.getItem('username') || 'system'
        }
        const res = await write.post('baseinfowrite/api/CargoOwner/UpdateCargoOwnerInfo', payload)
        const json = res?.data
        if (res?.status === 200 && (json?.code === 200 && (json?.data === true || json?.data === 1))) {
            window.location.href = '/GetCargoOwner?refresh=1'
        } else {
            console.error('更新失败', json)
        }
    } finally {
        submitting.value = false
    }
}

function handleCancel() { if (window.history.length > 1) window.history.back() }

onMounted(() => {
    const idParam = route.params.id || route.query.id
    const id = typeof idParam === 'string' ? Number(idParam) : Array.isArray(idParam) ? Number(idParam[0]) : Number(idParam)
    if (!Number.isNaN(id)) { form.id = id; loadDetail(id) }
    loadExternalUnits()
    // 等待下拉数据加载后，再次同步地址列表，确保详情值能显示
    setTimeout(syncAddressOptionsFromCompany, 300)
})
</script>

<style scoped>
.add-cargo-owner-page {
    padding: 16px 20px;
    color: #333;
    font-size: 14px;
}

.page-title {
    font-size: 18px;
    margin-bottom: 12px;
}

.card {
    background: #fff;
    border: 1px solid #e5e6eb;
    border-radius: 4px;
}

.form {
    padding: 16px;
    max-width: 720px;
}

.form-item {
    display: flex;
    align-items: center;
    margin-bottom: 14px;
}

.form-item.required .label::before {
    content: '*';
    color: #f56c6c;
    margin-right: 4px;
}

.label {
    width: 120px;
    color: #666;
}

.input {
    flex: 1;
    height: 32px;
    line-height: 32px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 0 10px;
}

.textarea {
    flex: 1;
    min-height: 120px;
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding: 8px 10px;
}

.upload-box {
    width: 210px;
    height: 160px;
    border: 1px dashed #dcdfe6;
    border-radius: 6px;
    display: flex;
    align-items: center;
    justify-content: center;
    cursor: pointer;
    position: relative;
    background: #fafafa;
}

.file-input {
    position: absolute;
    opacity: 0;
    width: 0;
    height: 0;
}

.uploader {
    text-align: center;
    color: #909399;
}

.plus {
    font-size: 36px;
    line-height: 1;
}

.preview {
    max-width: 100%;
    max-height: 100%;
    border-radius: 4px;
}

.form-actions {
    margin-top: 18px;
    display: flex;
    gap: 10px;
}

.btn {
    height: 32px;
    padding: 0 16px;
    border: 1px solid #dcdfe6;
    background: #fff;
    border-radius: 4px;
    cursor: pointer;
}

.btn.primary {
    background: #409eff;
    border-color: #409eff;
    color: #fff;
}

.btn:disabled {
    opacity: 0.6;
    cursor: not-allowed;
}
</style>
